﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ModuleITDesk.BLL;
using ModuleITDesk.DAL;
using ModuleITDesk.DAL.Model;
namespace ModuleITDesk
{
    public partial class CRAdmin : Form
    {
        ModuleITDeskEntities contextDB;
        BLLUsers userBLL = new BLLUsers();
        DALUser UserDAL = new DALUser();
        DALProject ProjectDAL = new DALProject();
        BLLProject ProjectBLL = new BLLProject();
        int AdminId = -1;
        string username = "";
        string password = "";
        public CRAdmin(int id,string adminname,string adminpassword)
        {
            InitializeComponent();
            contextDB = new ModuleITDeskEntities();
            AdminId = id;
            username = adminname;
            password = adminpassword;
        }
        private void LoadProjectList()
        {
            var list = from p in contextDB.Projects
                       from u in contextDB.Users
                       where p.UserID == u.UserID && u.Permission == 0
                       select new
                       {
                           projectid = p.ProjectID,
                           projectname = p.ProjectName,
                           createddate = p.CreatedDate,
                           customername = p.CustomerName,
                           activity = p.Activity,
                           hours = p.Hours,
                           percent = p.PercentToFinish,
                           billable = p.Billable,
                           whichinsolex = p.WhichInsolex,
                           cost = p.Cost,
                           username = u.UserName,
                           userid = u.UserID,
                           useremail=u.Email,
                           userfirstname=u.FirstName,
                           userlastname=u.LastName
                       };
            if (list.ToList() != null)
            {
                try
                {
                    dgvprojects.Rows.Clear();
                    foreach (var l in list)
                    {
                        dgvprojects.Rows.Add(l.projectid, l.username, l.createddate.ToString("MM/dd/yyyy"), l.customername, l.projectname, l.activity, l.billable, l.cost,l.hours, l.percent, l.whichinsolex,l.userfirstname,l.userlastname,l.useremail);
                    }
                    dgvprojects.Refresh();
                }
                catch (Exception ex)
                {
                    return; 
                }
            }
        }

        private void CRAdmin_Load(object sender, EventArgs e)
        {
            this.Visible = true;
            groupBoxemployee.Visible = true;
            groupBoxemployee.Visible = true;
            groupBoxAction.Visible = true;
            grbproject.Visible = true;
            groupBoxcalc.Visible = true;
            groupBoxchangedpass.Visible = false;
            btnchangedpassword.Enabled = true;
            cbosort.Items.Add("By Username");
            cbosort.Items.Add("By Customer name");
            cbosort.Items.Add("By Project");
            cbosort.Items.Add("By Date");
            cbosort.Items.Add("By Percent");
            LoadProjectList();
        }

        private void btnupdatetable_Click(object sender, EventArgs e)
        {
            LoadProjectList();
        }

        private void btnlogout_Click(object sender, EventArgs e)
        {
            this.Visible = false;
            CRMain crmain = new CRMain();
            crmain.ShowDialog();
        }

        private void cbosort_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbosort.Text == "By Username")
            {
                dgvprojects.Sort(this.dgvprojects.Columns["colUsername"], ListSortDirection.Ascending);
            }
            if (cbosort.Text == "By Customer name")
            {
                dgvprojects.Sort(this.dgvprojects.Columns["colCustomer"], ListSortDirection.Ascending);
            }
            if (cbosort.Text == "By Project")
            {
                dgvprojects.Sort(this.dgvprojects.Columns["colProject"], ListSortDirection.Ascending);
            }
            if (cbosort.Text == "By Date")
            {
                dgvprojects.Sort(this.dgvprojects.Columns["colCreatedDate"], ListSortDirection.Ascending);
            }
            if (cbosort.Text == "By Percent")
            {
                dgvprojects.Sort(this.dgvprojects.Columns["colPercent"], ListSortDirection.Ascending);
            }
        }

        private void dgvprojects_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowindex = dgvprojects.CurrentCell.RowIndex;
            txtprojectsID.Text = dgvprojects.Rows[rowindex].Cells["colProjectIID"].Value.ToString();
            txtusername.Text = dgvprojects.Rows[rowindex].Cells["colUsername"].Value.ToString();
            txtfirstname.Text = dgvprojects.Rows[rowindex].Cells["colFirstname"].Value.ToString();
            txtlastname.Text = dgvprojects.Rows[rowindex].Cells["colLastname"].Value.ToString();
            txtdatecreated.Text = dgvprojects.Rows[rowindex].Cells["colCreatedDate"].Value.ToString();
            txtcustomername.Text = dgvprojects.Rows[rowindex].Cells["colCustomer"].Value.ToString();
            txtprojects.Text = dgvprojects.Rows[rowindex].Cells["colProject"].Value.ToString();
            progressBar1.Value = int.Parse(dgvprojects.Rows[rowindex].Cells["colPercent"].Value.ToString());
            txtactivity.Text = dgvprojects.Rows[rowindex].Cells["colTask"].Value.ToString();
            txthours.Text = dgvprojects.Rows[rowindex].Cells["colHours"].Value.ToString();
            txtbillable.Text = dgvprojects.Rows[rowindex].Cells["colBillable"].Value.ToString();
            txtworkat.Text = dgvprojects.Rows[rowindex].Cells["colwhichsolex"].Value.ToString();
            txtmail.Text = dgvprojects.Rows[rowindex].Cells["colEmail"].Value.ToString();
            progressBar2.Value = int.Parse(dgvprojects.Rows[rowindex].Cells["colPercent"].Value.ToString());
        }

        private void btncheck_Click(object sender, EventArgs e)
        {
            DateTime datefrom = DateTime.Parse(dateTimePickerfrom.Text);
            DateTime dateto = DateTime.Parse(dateTimePickerto.Text);
            if(string.IsNullOrEmpty(txtprojectsort.Text) && string.IsNullOrEmpty(txtcustomernamesort.Text))
            {
                try
                {
                    var list = from p in contextDB.Projects
                               from u in contextDB.Users
                               where p.UserID == u.UserID 
                               && u.UserName == txtusernamesort.Text.Trim() 
                               && u.Permission == 0    
                               && p.CreatedDate.Day >=datefrom.Date.Day
                               && p.CreatedDate.Month >= datefrom.Date.Month
                               && p.CreatedDate.Year >= datefrom.Date.Year
                               && p.CreatedDate.Day <= dateto.Date.Day
                               && p.CreatedDate.Month <= dateto.Date.Month
                               && p.CreatedDate.Year <= dateto.Date.Year
                               select new
                               {
                                   projectid = p.ProjectID,
                                   projectname = p.ProjectName,
                                   createddate = p.CreatedDate,
                                   customername = p.CustomerName,
                                   activity = p.Activity,
                                   hours = p.Hours,
                                   percent = p.PercentToFinish,
                                   billable = p.Billable,
                                   whichinsolex = p.WhichInsolex,
                                   cost = p.Cost,
                                   username = u.UserName,
                                   userid = u.UserID,
                                   useremail = u.Email,
                                   userfirstname = u.FirstName,
                                   userlastname = u.LastName
                               };
                    if (list.ToList() != null)
                    {
                        var totalhours = list.Select(p => p.hours).Sum();
                        var totalcost = list.Select(p => p.cost).Sum();                       
                        try
                        {
                            dgvprojects.Rows.Clear();
                            foreach (var l in list)
                            {
                                dgvprojects.Rows.Add(l.projectid, l.username, l.createddate.ToString("MM/dd/yyyy"), l.customername, l.projectname, l.activity, l.billable, l.cost, l.hours, l.percent, l.whichinsolex, l.userfirstname, l.userlastname, l.useremail);
                            }                            
                            dgvprojects.Refresh();
                            txthoursort.Text = totalhours.ToString();
                            txtcostsort.Text = totalcost.ToString();
                        }
                        catch (Exception ex)
                        {
                            return;
                        }
                    }
                }
                catch { return; }
            }
            else if(string.IsNullOrEmpty(txtprojectsort.Text))
            {
                try
                {
                    var list = from p in contextDB.Projects
                               from u in contextDB.Users
                               where p.UserID == u.UserID 
                               && u.UserName == txtusernamesort.Text.Trim() 
                               && u.Permission == 0 
                               && p.CustomerName==txtcustomernamesort.Text.Trim()
                               && p.CreatedDate.Day >= datefrom.Date.Day
                               && p.CreatedDate.Month >= datefrom.Date.Month
                               && p.CreatedDate.Year >= datefrom.Date.Year
                               && p.CreatedDate.Day <= dateto.Date.Day
                               && p.CreatedDate.Month <= dateto.Date.Month
                               && p.CreatedDate.Year <= dateto.Date.Year
                               select new
                               {
                                   projectid = p.ProjectID,
                                   projectname = p.ProjectName,
                                   createddate = p.CreatedDate,
                                   customername = p.CustomerName,
                                   activity = p.Activity,
                                   hours = p.Hours,
                                   percent = p.PercentToFinish,
                                   billable = p.Billable,
                                   whichinsolex = p.WhichInsolex,
                                   cost = p.Cost,
                                   username = u.UserName,
                                   userid = u.UserID,
                                   useremail = u.Email,
                                   userfirstname = u.FirstName,
                                   userlastname = u.LastName
                               };
                    if (list.ToList() != null)
                    {
                        var totalhours = list.Select(p => p.hours).Sum();
                        var totalcost = list.Select(p => p.cost).Sum();
                        try
                        {
                            dgvprojects.Rows.Clear();
                            foreach (var l in list)
                            {
                                dgvprojects.Rows.Add(l.projectid, l.username, l.createddate.ToString("MM/dd/yyyy"), l.customername, l.projectname, l.activity, l.billable, l.cost, l.hours, l.percent, l.whichinsolex, l.userfirstname, l.userlastname, l.useremail);
                            }
                            dgvprojects.Refresh();
                            txthoursort.Text = totalhours.ToString();
                            txtcostsort.Text = totalcost.ToString();
                        }
                        catch (Exception ex)
                        {
                            return;
                        }
                    }
                }
                catch { return; }
            }
            else
            {
                try
                {
                    var list = from p in contextDB.Projects
                               from u in contextDB.Users
                               where p.UserID == u.UserID 
                               && u.UserName == txtusernamesort.Text.Trim() 
                               && u.Permission == 0 
                               && p.CustomerName == txtcustomernamesort.Text.Trim() 
                               && p.ProjectName==txtprojectsort.Text.Trim()
                               && p.CreatedDate.Day >= datefrom.Date.Day
                               && p.CreatedDate.Month >= datefrom.Date.Month
                               && p.CreatedDate.Year >= datefrom.Date.Year
                               && p.CreatedDate.Day <= dateto.Date.Day
                               && p.CreatedDate.Month <= dateto.Date.Month
                               && p.CreatedDate.Year <= dateto.Date.Year
                               select new
                               {
                                   projectid = p.ProjectID,
                                   projectname = p.ProjectName,
                                   createddate = p.CreatedDate,
                                   customername = p.CustomerName,
                                   activity = p.Activity,
                                   hours = p.Hours,
                                   percent = p.PercentToFinish,
                                   billable = p.Billable,
                                   whichinsolex = p.WhichInsolex,
                                   cost = p.Cost,
                                   username = u.UserName,
                                   userid = u.UserID,
                                   useremail = u.Email,
                                   userfirstname = u.FirstName,
                                   userlastname = u.LastName
                               };
                    if (list.ToList() != null)
                    {
                        var totalhours = list.Select(p => p.hours).Sum();
                        var totalcost = list.Select(p => p.cost).Sum();
                        try
                        {
                            dgvprojects.Rows.Clear();
                            foreach (var l in list)
                            {
                                dgvprojects.Rows.Add(l.projectid, l.username, l.createddate.ToString("MM/dd/yyyy"), l.customername, l.projectname, l.activity, l.billable, l.cost, l.hours, l.percent, l.whichinsolex, l.userfirstname, l.userlastname, l.useremail);
                            }
                            dgvprojects.Refresh();
                            txthoursort.Text = totalhours.ToString();
                            txtcostsort.Text = totalcost.ToString();
                        }
                        catch (Exception ex)
                        {
                            return;
                        }
                    }
                }
                catch { return; }
            }
        }
        private void ChangedPassword()
        {
            if (userBLL.ChangedPassword(username,txtoldpass.Text, txtnewpass.Text))
            {
                MessageBox.Show("Password changed successfull", "Warning");
                groupBoxchangedpass.Visible = false;
                groupBoxemployee.Visible = true;
                groupBoxemployee.Visible = true;
                groupBoxAction.Visible = true;
                grbproject.Visible = true;
                groupBoxcalc.Visible = true;
                groupBoxchangedpass.Dock = DockStyle.None;
                btnchangedpassword.Enabled = false;
            }
            else
            {
                MessageBox.Show("Password changed fail, Try again", "Warning");
            }

        }

        private void btnchangedpassword_Click(object sender, EventArgs e)
        {
            groupBoxemployee.Visible = false;
            groupBoxemployee.Visible = false;
            groupBoxAction.Visible = false;
            grbproject.Visible = false;
            groupBoxcalc.Visible = false;
            groupBoxchangedpass.Visible = true;
            groupBoxchangedpass.Dock = DockStyle.Left;
            txtoldpass.Text = password;
        }

        private void btnsubmit_Click(object sender, EventArgs e)
        {
            ChangedPassword();
        }
    }
}
